package com.zhengyisky;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 将被代理对象(目标对象)注入到代理对象中
 */
public class JdkProxy implements InvocationHandler {

    //目标对象、被代理对象、真实对象
    private Object targetObject;

    public Object initProxyObject(Object targetObject){
        this.targetObject = targetObject;
        //通过反射为被代理对象创建代理对象
        Object proxyObject = Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), this);
        return proxyObject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long t1 = System.currentTimeMillis();

        Object o = method.invoke(targetObject);

        long t2 = System.currentTimeMillis();
        System.out.println(t2-t1);
        return o;
    }
}
